package com.example.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.system.entity.Health;
import com.example.system.entity.User;
import com.example.system.exception.CustomException;
import com.example.system.mapper.HealthMapper;
import com.example.system.mapper.UserMapper;
import com.example.system.service.IHealthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class HealthServiceImpl extends ServiceImpl<HealthMapper, Health> implements IHealthService {
    @Autowired
    private HealthMapper healthMapper;
    @Autowired
    private UserMapper userMapper;

    public List<Health> findHealthByUserID(Integer userId) {
        return healthMapper.findHealthByUserID(userId);
    }

    public void addHealthByHealth(Health health) {
        //护理ID一定不能为空
        if (health.getUserId() == null) {
            throw new CustomException("用户信息Id不能为空");
        }
        if (!userMapper.existsUserById(health.getUserId())) {
            throw new CustomException("当前用户ID不存在");
        }
        if (healthMapper.existsHealthKeyPair(health.getUserId(), health.getHealthId())) {
            throw new CustomException("健康表中已存在当前使用的复合键");
        }
        healthMapper.addHealthByHealth(health);
    }

    public List<Health> findHealthByUserIDAndTimeRange(Integer userId, LocalDateTime beginTime, LocalDateTime endTime) {
        if (userId == null) {
            throw new CustomException("用户信息Id不能为空");
        }
        if (!userMapper.existsUserById(userId)) {
            throw new CustomException("当前用户ID不存在");
        }
        if (beginTime.isAfter(endTime)) {
            throw new CustomException("开始时间不能大于结束时间");
        }
        return healthMapper.findHealthByUserIDAndTimeRange(userId, beginTime, endTime);
    }

    public void deleteHealthByUserIdAndTimeRange(Integer userId, LocalDateTime beginTime, LocalDateTime endTime) {
        if (userId == null) {
            throw new CustomException("用户信息Id不能为空");
        }
        if (!userMapper.existsUserById(userId)) {
            throw new CustomException("当前用户ID不存在");
        }
        if (beginTime.isAfter(endTime)) {
            throw new CustomException("开始时间不能大于结束时间");
        }
        healthMapper.deleteHealthByUserIdAndTimeRange(userId, beginTime, endTime);
    }

    public void deleteHealthByUserId(Integer userId) {
        if (userId == null) {
            throw new CustomException("用户信息Id不能为空");
        }
        if (!userMapper.existsUserById(userId)) {
            throw new CustomException("当前用户ID不存在");
        }
        healthMapper.deleteHealthByUserId(userId);
    }
}
